/**
 * 使用 useCallback 优化 获取后台数据 渲染列表
 */

import React, { useState, useEffect, useCallback } from 'react';
import styled from 'styled-components';
import { getDemoList } from '../service/homeData';
import Loading from '../components/Loading';

function RenderLis2() {
  const [loading, setloading] = useState(false);
  const [list, setlist] = useState([]);

  // 仅在list发生变化时才重新执行
  const addMoreCallBack = useCallback(() => {
    setloading(true);
    getDemoList()
      .then((data) => {
        setlist([...list, ...data]);
      })
      .finally(() => {
        setloading(false);
      });
  }, [list]);

  useEffect(() => {
    addMoreCallBack();
  }, []);

  return (
    <RenderLis2Container>
      <div className="content-list">
        <ul className="list">
          {list.map(({ id, content }) => (
            <li key={id} className="list-item">
              {id} - {content}
            </li>
          ))}
        </ul>
        {!!list.length && !loading && (
          <button onClick={addMoreCallBack} className="add-more">
            加载更多 useCallBack
          </button>
        )}
      </div>
      {loading && <Loading></Loading>}
    </RenderLis2Container>
  );
}

const RenderLis2Container = styled.div`
  padding: 20px;
  border: 1px solid #eee;
  .list {
  }
  .list-item {
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
  .add-more {
    padding: 5px 10px;
  }
`;

export default RenderLis2;
